package com.opgea.tutor.util;

import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.opgea.tutor.domain.constants.SessionConstants;
import com.opgea.tutor.domain.model.UserSessionData;
import com.opgea.tutor.web.dto.LoginDTO;

public class FacesUtil {

    public static ExternalContext getExternalContext() {
	ExternalContext extContext = FacesContext.getCurrentInstance()
		.getExternalContext();
	return extContext;
    }

    public static HttpSession getHttpSession() {
	HttpSession session = (HttpSession) getExternalContext().getSession(
		true);
	return session;
    }

    public static UserSessionData getSessionUserDataObject() {
	if (getHttpSession().getAttribute(SessionConstants.SESSION_DATA) != null) {
	    return (UserSessionData) getHttpSession().getAttribute(
		    SessionConstants.SESSION_DATA);
	} else {
	    UserSessionData sessionData = new UserSessionData();
	    getHttpSession().setAttribute(SessionConstants.SESSION_DATA,
		    sessionData);
	    return sessionData;
	}
    }

    public static LoginDTO getLoginDTOFromSession() {
	UserSessionData sessionData = getSessionUserDataObject();
	LoginDTO loginDTO = new LoginDTO();
	loginDTO.setId(sessionData.getLoginIdPrimaryKey());
	loginDTO.setLoginId(sessionData.getLoginId());
	loginDTO.setUserType(sessionData.getUserType());
	return loginDTO;
    }

    public static void addMessage(String messageId,
	    FacesMessage.Severity severity, String summaryMessage,
	    String detailedMessage) {
	FacesMessage facesMessage = new FacesMessage(severity, summaryMessage,
		detailedMessage);
	FacesContext.getCurrentInstance().addMessage(messageId, facesMessage);
    }

    public static HttpServletRequest getHttpServletRequest() {
	ExternalContext context = FacesContext.getCurrentInstance()
		.getExternalContext();
	return (HttpServletRequest) context.getRequest();
    }

    public static HttpServletResponse getHttpServletResponse() {
	ExternalContext context = FacesContext.getCurrentInstance()
		.getExternalContext();
	return (HttpServletResponse) context.getResponse();
    }

    public static String getPageName() {
	String pathName = getHttpServletRequest().getPathInfo();
	return pathName.substring(pathName.lastIndexOf("/") + 1,
		pathName.lastIndexOf("."));
    }

    public static Object getParameter(String paramName) {
	return getExternalContext().getRequestMap().get(paramName);
    }

    public static String getRequestParameter(String paramName) {
	return getHttpServletRequest().getParameter(paramName);
    }
}
